<template>
   <el-row :gutter="20" @next="nextPage">
     <el-col   :xs="{span:20,push:2}" :sm="{span:12,push:7}" :md="{span:10,push:7}" :lg="{span:8,push:8}" >
       <el-card shadow="always" :body-style="{ padding: '20px' }">
         <el-form :model="verification" ref="userForm" :rules="rules" label-width="80px" :inline="false" size="normal">
           <el-form-item label="邮箱：" prop="email">
             <el-input type="text" v-model="verification.email" ></el-input>
           </el-form-item>
          <el-form-item label="验证码：" prop="code">
             <el-input type="text" v-model="verification.code" ></el-input>
          </el-form-item>
          <el-row >
            <el-col :span="24"  :style="{'text-align':'center'}">
              <el-button  type="primary" @click="onSubmit">提交</el-button>
              <el-button   class="hidden-xs-only" type="primary" @click="getCode" :disabled="isCode">{{butMsg}}</el-button>
            </el-col>
          </el-row>
          <el-row  class="hidden-sm-only hidden-md-only hidden-sm-only hidden-lg-only hidden-xl-only"  :style="{'margin-top':'10px'}">
            <el-col :span="24"  :style="{'text-align':'center'}">
              <el-button   type="primary" @click="getCode" :disabled="isCode">{{butMsg}}</el-button>
            </el-col>
          </el-row>
         </el-form>
       </el-card>
     </el-col>
   </el-row>
</template>

<script lang="ts">
  import { Component, Vue, Ref , Emit } from 'vue-property-decorator';
  import {ElForm,ValidateCallback,ValidateFieldCallback} from 'element-ui/types/form';
  import Verification from '@/domain/Verification';
  import http from '@/utils/request';
  import {AxiosResponse} from "axios"
  import Rules,{Validator,Rule} from '@/domain/Rules';
  import VerificationType from "@/domain/VerificationType"



  //字符串中含有空字符
  let trimValidator:Validator=(rules:any,value:string,calllback:Function):void=>{
             if (value.length>value.trim().length) {
               calllback(new Error('不能含有空格'));
               return;
             }
             calllback();
  };

//  密码校验规则
  const  codeValidatorArr:Array<Rule>=[
          {
          "trigger":"change",
          "required":true,
          "message":"请输入验证码"
          },
          {
          "trigger":"change",
          "min":6,
          "max":6,
          "message":"验证码字符必须是6位"
          },
          {
          "trigger":"change",
          "validator":trimValidator,
          "message":"验证码不能存在空字符"
          },
        ];

// 邮箱校验规则
const emailValidatorArr:Array<Rule>=[
          {
          "trigger":"change",
          "required":true,
          "message":"请输入邮箱"
          },
          {
          "trigger":"change",
          "min":1,
          "max":20,
          "message":"邮箱字符限制在20个字符内"
          },
          {
          "type":"email",
          "trigger":"change",
          "message":"不符合邮箱格式"
          },
        ];


   @Component
   class AdminCheck extends Vue {
      // 验证码校验集合
      verification:Verification={email:"",code:undefined,type:VerificationType.RESET_PASSWORD};
      // 参数校验规则
      readonly rules:Rules={
        "email":emailValidatorArr,
        "code":codeValidatorArr
      };

      isCode:boolean = false;
      time:number = 120;
      butMsg:string ='获取验证码';

      @Ref('userForm')  readonly userform!:ElForm;

      onSubmit():void{
        //参数校验
        let  callback:ValidateCallback= (isValid: boolean, invalidFields: object): void=>{
          if(isValid){
            http({
              url:'/user/checkVerificationCode',
              method:'POST',
              data:this.verification
            }).then((resp:AxiosResponse):void=>{
                 localStorage.setItem('token',resp.data);
                 this.nextPage();
            });
            
            return;
          }
          console.error('请求参数校验失败')
        };
        this.userform.validate(callback)
      }

      getCode():void{

        let  callback:ValidateFieldCallback= (errorMessage: string): void=>{
          if(!errorMessage){
            http({
              url:'/user/verificationCode',
              method:'get',
              params:this.verification
            }).then((resp:AxiosResponse):void=>{
              this.isCode = true;
              this.setTime();
            })            
            return;
          }
          console.error('请求参数校验失败')
        };
        this.userform.validateField(['email'],callback)
      }

      setTime():void{
          if(this.time==0){
            this.isCode = false;
            this.butMsg = '获取验证码';
            return;
          }
          setTimeout(() => {
            this.time--;
            this.butMsg='获取验证码('+this.time+')'
            this.setTime();
          }, 1000);
      }

      @Emit('next')
      nextPage():number{
        return 1;
      }


  }
  export default AdminCheck;
</script>
